<?php

namespace Aspic\Resource;
use Aspic\File\File;


/**
 * Retrieve resource from file
 *
 * @package Aspic\Resource
 */
class FileResourceLocator implements ResourceLocatorInterface
{

    const ASPIC_RESOURCE_PATH = __DIR__ . '/../../resource';

    protected $paths;
    protected $exts;

    function __construct(array $paths = array(), array $exts = array('php', 'html', 'js'), $addAspicResourcePath = true)
    {
        if ($addAspicResourcePath) {
            array_unshift($paths, static::ASPIC_RESOURCE_PATH);
        }

        $this->paths = $paths;
        $this->exts = $exts;
    }

    public function addPath($path)
    {
        $this->paths[] = $path;
    }

    /**
     * @param $resourceName
     * @return string
     */
    protected function getResourceNameToFilePath($resourceName)
    {
        foreach ($this->paths as $path) {
            foreach ($this->exts as $ext) {
                $resourcePath = $path . '/' . $resourceName . '.' . $ext;

                if (is_file($resourcePath)) {
                    return $resourcePath;
                }
            }

        }
    }

    /**
     * Get the content of a resource
     *
     * @param $resourceName
     * @return bool|string
     */
    public function getResource($resourceName)
    {
        $resourcePath = $this->getResourceNameToFilePath($resourceName);

        $cts = File::getContents($resourcePath);

        return $cts;
    }
}